import { readdirSync } from 'fs'
import { taroBuildStr, wepyBuildStr, wepyEnv } from './config'

interface BuildProject {
  runType: 'watch' | 'build'
  env: 'prod' | 'uat' | 'dev'
  dir: string
}

export const buildProject = ({ dir, env, runType }: BuildProject): { cmdStr: string, opt: any } => {
  const cwd = process.cwd()
  const list = readdirSync(cwd)
  const typeMap = {
    'tsconfig.json': 'taro',
    'wepy.config.js': 'wepy'
  }
  const filename = list.find(item => ['tsconfig.json', 'wepy.config.js'].includes(item)) as 'tsconfig.json' | 'wepy.config.js'
  const type = typeMap[filename]

  let cmdStr: string, opt: string
  switch (type) {
    case 'taro':
      opt = '../../'
      cmdStr = `${taroBuildStr[runType]} --dir=p2762 --env=prod`
      break
    case 'wepy':
      opt = ''
      cmdStr = `npx cross-env NODE_ENV=production API_ENV=${wepyEnv[env]} HIS_ID=${dir} wepy ${wepyBuildStr[runType]}`
      break
    default:
      throw new Error('获取项目类型失败')
  }

  return { opt, cmdStr }
}
